//
// Description: 380. O(1) 时间插入、删除和获取随机元素
// Created by Loading on 2025/3/2.
//

#include <bits/stdc++.h>

using namespace std;

class RandomizedSet {
public:
    RandomizedSet() {
        srand(time(nullptr));
    }

    bool insert(int val) {
        if (m_index.count(val)){ // 下标已存在
            return false;
        }
        nums.emplace_back(val);
        m_index[val] = nums.size() - 1;

        return true;
    }

    bool remove(int val) {
        if (!m_index.count(val)) { // 下标不存在
            return false;
        }
        int index = m_index[val];
        // 将数组的最后一个元素移至index位置
        nums[index] = nums.back();
        // 更新map索引
        m_index[nums.back()] = index;
        // 移除val
        nums.pop_back();
        m_index.erase(val);

        return true;
    }

    int getRandom() {
        int index = rand()%nums.size();
        return nums[index];
    }
private:
    vector<int> nums;
    unordered_map<int, int> m_index; // val-下标
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */

int main() {
    auto obj = new RandomizedSet;
    bool res1 = obj->insert(1);
    bool res2 = obj->remove(2);
    bool res3 = obj->insert(2);
    int res4 = obj->getRandom();

    cout << res1 << ' ' << res2 << ' ' << res3 << ' ' << res4;

    return 0;
}
